#!/bin/sh /etc/rc.common
# SPDX-License-Identifier: MIT

##########################################################################
#
# Copyright (C) 2019-2020 Tano Systems LLC. All rights reserved.
# Anton Kikin <a.kikin@tano-systems.com>
#
##########################################################################

START=00

USE_PROCD=1

PSPLASH_TMPDIR="/tmp/psplash"
PSPLASH_ANGLE_FILE="/etc/rotation"
PSPLASH_BIN="/usr/bin/psplash"
PSPLASH_ARGS=""
PSPLASH_INIT_SCRIPTS="/etc/psplash-init.d"

psplash_init()
{
	local CMDLINE

	read CMDLINE < /proc/cmdline
	for x in $CMDLINE; do
		case $x in
			psplash=false)
				echo "Boot splashscreen disabled by 'psplash=false'"
				exit 0;
			;;
		esac
	done

	# Run custom init scripts
	if [ -d "${PSPLASH_INIT_SCRIPTS}" ]; then
		local files
		files=`ls -1 "${PSPLASH_INIT_SCRIPTS}"`
		for file in $files; do
			source ${PSPLASH_INIT_SCRIPTS}/$file
		done
	fi
}

start_service()
{
	local angle
	local angle_file

	psplash_init

	config_load "psplash"

	config_get angle 'config' 'rotation' 0
	config_get fbdev_id 'config' 'fbdev_id' 0
	config_get angle_file 'config' 'rotation_file' ${PSPLASH_ANGLE_FILE}

	if [ ! -e "/dev/fb${fbdev_id}" ]; then
		echo "Framebuffer /dev/fb${fbdev_id} not detected"
		echo "Boot splashscreen disabled"
		exit 0;
	fi

	if [ -n "$angle_file" -a -e "${angle_file}" ]; then
		read angle < "${angle_file}"
	fi

	[ -n "$angle" ] || angle=0

	case $angle in
		0|90|180|270)
			PSPLASH_ARGS="--angle ${angle}"
			;;
	esac

	if [ ! -x "${PSPLASH_BIN}" ]; then
		exit 0
	fi

	mkdir -p ${PSPLASH_TMPDIR}

	procd_open_instance
	procd_set_param command ${PSPLASH_BIN} ${PSPLASH_ARGS}
	procd_set_param env TMPDIR=${PSPLASH_TMPDIR}
	procd_set_param stderr 1
	procd_close_instance
}

service_running()
{
	pgrep "psplash" &> /dev/null
}

# Manual stop psplash
stop_service()
{
	running || return 1
	TMPDIR=${PSPLASH_TMPDIR} psplash-write "QUIT"
}
